<?php


function Web_output(){
    global $_G,$AppId;
    if (defined('SING_OUTPUTED')) {
        return;
    } else {
        define('SING_OUTPUTED', 1);
    }

    $content = ob_get_contents();
    ob_end_clean();

    $_G['gzipcompress'] ? ob_start('ob_gzhandler') : ob_start();
    
    $content = str_replace('</head>',"<script src=\"http://res.wx.qq.com/open/js/jweixin-1.0.0.js\" ></script>\n<script src=\"http://".$AppId.".webwx.sichem.cn/app/weixinjsbridge/?inajax=1&url=".  Web_urlencodebug($_G['FULL_URL'])."\" ></script>\n</head>",$content);
    //$jsapi_ticket = GetJsapi_ticket('SPEGEKIGFN');
    //if($jsapi_ticket){
        //$noncestr = createNonceStr();
        //$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        //$buff = array('noncestr'=>$noncestr,'jsapi_ticket'=>$jsapi_ticket,'timestamp'=>TIME,'url'=>$url);
        //$str = formatBizQueryParaMap($buff, false);
       // $_G['jsapi']['signature'] = sha1($str);
   // }
    

   switch($_GET['do']){
		case 'index':
			if($_GET['s'] == 'show'){
				$content = str_replace('</head>','<script>function NewShare(){$.post(\'/app/integral/sharenews\',{id:'.$_GET['id'].'});}</script></head>',$content);
                                $content = str_replace('</head>','<script src="/static/common/js/wx_public.js"></script></head>',$content);//点击量 赞 评论 等公用js
			}
			break;
	}
    echo $content;
}

function Web_inituser($_mid, $openid = ''){
    global $_G;
    $clientkey = getcookie('authkey_'.$_mid);
    list($openid, $mid ,$subscribe) = explode("\t", SING_auth($clientkey,'DECODE',getglobal('cookiepre','config/cookie')));
    if(!is_weixin()) return;
    if(!$openid && $_GET['do'] != 'weixinjsbridge'){
        $url = 'http://user.wx.sichem.cn/'.$_mid.'?url='.urlencode($_G['FULL_URL']);
        if($_GET['jumpurl']) $url .= '&jumpurl='.urlencode($_GET['jumpurl']);
        if($_GET['code']) $url .= '&code='.$_GET['code'];
        header('Location: ' . $url);
        exit;
    }else{
        $_G[$_mid]['openid'] = $openid;
	$_G[$_mid]['subscribe'] = $subscribe;
        if($_GET['jumpurl']){
            
            if (stripos($_GET['jumpurl'], '?') !== false) {
                $jurl = explode('?', $_GET['jumpurl']);   //问号以后是参数提取出来
                if ($jurl[1]) {   //这里是所有参数的字符串组合
                    $key = explode('&', $jurl[1]); //拆分
                    foreach ($key as $v) {
                        if ($v){
                            $strkey = explode('=', $v);
                            if ($strkey[0] != 'code') $lstr[] = $v;
                        }                                
                    }
                    unset($key);
                }
                $lstr[] = 'clientkey='.urlencode($clientkey);
                if(count($lstr)) $key = implode('&', $lstr);
                $url = $jurl[0] .($key? '?' . $key :'');
            }else{
                $lstr[] = 'clientkey='.urlencode($clientkey);
                if(count($lstr)) $key = implode('&', $lstr);
                $url = $_GET['jumpurl'] .($key? '?' . $key :'');
            }            
            header('Location: ' . $url);
            exit;
        }
    }
    
    $_G[$_mid]['sopenid'] = $clientkey = getcookie('sopenid'.$_mid);
    if($_GET['sopenid'] && empty($_G[$_mid]['sopenid']) && $_GET['sopenid'] != $_G[$_mid]['openid']){
        $_G[$_mid]['sopenid'] = $_GET['sopenid'];
        dsetcookie('sopenid'. $_mid, $_GET['sopenid']);
    }
    //结尾处加推荐人的openid
    if (!$_G['inajax'] && is_weixin() && $_G[$_mid]['openid'] && (strlen($_GET['sopenid']) == 0 || $_GET['sopenid'] != $_G[$_mid]['openid'])) {
        $lstr = array();
        $So = false;
        if (stripos($_G['FULL_URL'], '?') !== false) { //如果有 ？号
            $jurl = explode('?', $_G['FULL_URL']);   //问号以后是参数提取出来
            //echo $jurl[1];
            if ($jurl[1]) {   //这里是所有参数的字符串组合
                $key = explode('&amp;', $jurl[1]); //拆分

                foreach ($key as $v) {
                    if ($v)
                        $strkey = explode('=', $v);
                    if ($strkey[0] == 'sopenid') {
                        $So = true;
                        $lstr[] = 'sopenid=' . $_G[$_mid]['openid'];
                    } elseif ($strkey[0] != 'redirect')
                        $lstr[] = $v;
                }
                if ($So == false)
                    $lstr[] = 'sopenid=' . $_G[$_mid]['openid'];
                $lstr[] = 'redirect=1';
            }
            $key = implode('&', $lstr);
            $url = $jurl[0] . '?' . $key;
        }else { //没有问号的情况
            $url = $_G['FULL_URL'] . '?sopenid=' . $_G[$_mid]['openid'] . '&redirect=openid-tj';
        }
        if (!$_G['inajax'] && empty($_GET['inajax'])) {
            header('Location: ' . $url);
            exit;
        }
    }
    
    $tjr = $_G[$_mid]['sopenid'] ? $_G[$_mid]['sopenid'] : '';

    if ($_G[$_mid]['openid']) {
        DB::insert('wx_soure', array(
            'tj_openid' => $tjr,
            'btj_openid' => $_G[$_mid]['openid'],
            'type' => $_GET['do'],
            'sid' => ($_GET['id'] ? intval($_GET['id']) : $_GET['s']),
            'mid' => $_mid,
            'inputtime' => TIME,
            'wxfrom' => $_GET['from'],
            'extinfo' => array2string($_GET)
        ));
    }
}
function Web_urlencodebug($url) {
    $url = str_replace('%26amp%3B', '%26', urlencode($url));
    return $url;
}

function formatBizQueryParaMap($paraMap, $urlencode){
	$buff = "";
	ksort($paraMap);
	foreach ($paraMap as $k => $v)
	{
		if($urlencode)
		{
		   $v = urlencode($v);
		}
		//$buff .= strtolower($k) . "=" . $v . "&";
		$buff .= $k . "=" . $v . "&";
	}
	$reqPar;
	if (strlen($buff) > 0) 
	{
		$reqPar = substr($buff, 0, strlen($buff)-1);
	}
	return $reqPar;
}
function wxThumb($src, $w , $h){
	global $_G;
	
	if(empty($src)) return 'NULL';
	$CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(APP_ROOT."/Conf/ue.config.json")), true);
	/*
	* 生成缩略图
	*/
	set_time_limit(0);	
	/* 上传配置 */
	$config = array(
		"pathFormat" => $CONFIG['catcherPathFormat'],
		"allowFiles" => $CONFIG['catcherAllowFiles'],
		"path"=>"upload/wx2014/image/{_uid}/{mid}/thumb/".md5($src),
		"width"=>$w,
		"height"=>$h
	);
	if (strpos($src, "http") === 0){
		$item = new Uploader($src, $config, "ossthumb");
	}else{
		$item = new Uploader($src, $config, "thumb");
	}
	
	$info = $item->getFileInfo();
	return $info["url"];
}

function getUser($openid, $mid){
	return C::t('#weixin#user')->get($openid,$mid);	
}

//替换url   这个方法复制修改时到apifunction一份 2015年11月30日 09:52:47
function aurl($url = '', $mid = ''){
	global $_G;
	if(!trim(strip_tags($url))) return '#';
	$HOST_URL = $_G['HOST_URL'];//主机地址
	$PRE1 = 'http://';//http
	$PRE2 = $HOST_URL.'app/';
	//要被替换的地址
	$array1 = array(
				$PRE1.'index/show/',
				$PRE1.'index',
				/*--------------------*/
				$PRE1.'member/cancelorder/',
				$PRE1.'member/logistics/',
				$PRE1.'member/orderconfirm/',
				$PRE1.'member/order_detail/',
				$PRE1.'member/order_gift/',
				$PRE1.'member/applyover/',
				$PRE1.'member/cancelapply/',
				$PRE1.'member/applymessage/',
				$PRE1.'member/apply/',
				/*------------------------*/
                $PRE1.'seckill/index',//秒杀首页
				$PRE1.'seckill/loadajax/',
				$PRE1.'member/index/',//会员中心首页
				$PRE1.'member/edit',
				$PRE1.'member/distribution_apply/',
				$PRE1.'member/distribution/',
				$PRE1.'member/collect',
				$PRE1.'member/charge_log',
				$PRE1.'member/orderpai_view/',
				$PRE1.'member/orderpai/',
				$PRE1.'member/pai_log/',
				$PRE1.'member/cash_log/',
				$PRE1.'member/order_view/',
				$PRE1.'member/order_check/',
				$PRE1.'member/order/',
				$PRE1.'member/sign_in',
				$PRE1.'member/integral_list',
				$PRE1.'member/coupon_view/',
				$PRE1.'member/coupon_check/',
				$PRE1.'member/coupon/',
				$PRE1.'member/address/',//收货地址列表
				$PRE1.'member/address_add/',//添加收货地址
				$PRE1.'member/address_edit/',//修改收货地址
				$PRE1.'member/collection/',//我的收藏
				$PRE1.'member/discountvoucher/',//我的收藏
				$PRE1.'member/discountvoucher_view/',//我的收藏
				$PRE1.'member/register/',//会员注册
				$PRE1.'member/login/',//会员登录
				$PRE1.'member',
				$PRE1.'albums?',
				$PRE1.'albums/',
				$PRE1.'album/',
				$PRE1.'list/',
				$PRE1.'news?',
				$PRE1.'news/',
				$PRE1.'form/',
				$PRE1.'card/',
				$PRE1.'scan/',
				$PRE1.'reserve',
				$PRE1.'sign/',
				$PRE1.'eshop/index/',//商城首页
				$PRE1.'eshop/show/',//商城商品详细
				$PRE1.'eshop/cart/',//商城购物车
				$PRE1.'eshop/category/',//商城分类列表
				$PRE1.'eshop/tag/',//商城标签列表
				$PRE1.'eshop/category_navigation/',//商城分类导航
				$PRE1.'eshop/navigation/',//商城导航
				$PRE1.'eshop/search/',//商城筛选
				$PRE1.'eshop/search_ajax/',//商城筛选
				$PRE1.'eshop/seminar/',//商城专题
				$PRE1.'eshop/store_manage/',
				$PRE1.'eshop/store_index/',
				$PRE1.'eshop/surroundings',
                $PRE1.'mate/index/',//商城商品详细
				$PRE1.'order/order_getaddr',//订单地址
				$PRE1.'order/order_gift_blessing',//礼物祝福页
				$PRE1.'order/order_gift_send',//礼物分享页
				$PRE1.'order/order_gift_view',//礼物查看页
				$PRE1.'order/order_gift_get',//礼物领取页
                                $PRE1.'order/order_gift_send1',//礼物分享页
				$PRE1.'order/order_gift_view1',//礼物查看页
				$PRE1.'ggk/',
				$PRE1.'lottery/',
				$PRE1.'active/',
				$PRE1.'cv/',
				$PRE1.'cv?',
				$PRE1.'present_info?',
				$PRE1.'present_get?',
				$PRE1.'present_doget?',
				$PRE1.'present_view?',
				$PRE1.'present_list?',
				$PRE1.'game/',
				$PRE1.'crm/login/',
				$PRE1.'task/index',
				$PRE1.'bonuses/pt/',
				$PRE1.'bonuses/Dbonuses/',
				$PRE1.'bonuses/hblist/',
				$PRE1.'distribution/index/',
				$PRE1.'distribution/apply/',
				$PRE1.'distribution/manage/',
				$PRE1.'distribution/shop/',
            $PRE1.'distribution/myshop/',
				$PRE1.'distribution/edit/',
				$PRE1.'distribution/member/',
            $PRE1.'distribution/deposit/',//店铺验证
				$PRE1.'manifesto/index/',
				$PRE1.'manifesto/makepic/',
				$PRE1.'manifesto/showpic/',
				$PRE1.'sharepage/index/',
				$PRE1.'sharepage/getnum/',
				$PRE1.'sharepage/receiveprize/',
				$PRE1.'survey/index/',
				$PRE1.'survey/show/',
				$PRE1.'survey/rank/',
				$PRE1.'survey/content/',
				$PRE1.'vote/index/',
				$PRE1.'vote/option/',
				$PRE1.'coupon/category/',
				$PRE1.'coupon/show/',
				$PRE1.'coupon/buy/',
				$PRE1.'coupon/pay/',
                $PRE1.'cfund/index',//众筹首页
                $PRE1.'cfund/cfund_detail',//众筹项目详细
                $PRE1.'cfund/support',//众筹 支持列表
                $PRE1.'cfund/support_detail',//众筹 支持详细
                $PRE1.'cfund/my_item',//众筹我的项目与关注
                $PRE1.'cfund/pay',
				$PRE1.'cfund/showMsg',
				$PRE1.'wxpay/index',
				$PRE1.'wxpay/helppayapply/',
				$PRE1.'wxpay/helppay/',
				$PRE1.'wxpay/recharge',
				$PRE1.'cfund/do_ajaxsigned',
            $PRE1.'estate/index',
            $PRE1.'estate/change',
            $PRE1.'estate/login',
            $PRE1.'estate/login_authorize',
            $PRE1.'estate/logout',
            $PRE1.'estate/lead/',
            $PRE1.'garden/index',
            $PRE1.'garden/change',
            $PRE1.'garden/login',
            $PRE1.'garden/login_authorize',
            $PRE1.'garden/logout',
            $PRE1.'garden/outstock_send',
            $PRE1.'park/joinpark',
            $PRE1.'park/maintain/',
            $PRE1.'newrss/index/',
            $PRE1.'outlink/index/',
            $PRE1.'webticket/index/',
            $PRE1.'webticket/login/',
			$PRE1.'webticket/accLogin/',
				$PRE1.'outlet/index/',
				$PRE1.'outlet/lead/',
				$PRE1.'outlet/change/',
				$PRE1.'outlet/login/',
				$PRE1.'outlet/login_authorize/',
				$PRE1.'outlet/logout/',
				$PRE1.'outlet/operate/',
				$PRE1.'outlet/scanEwm/',
				$PRE1.'outlet/testScan/',
				$PRE1.'outlet/cart_add/',
				$PRE1.'outlet/order/',
				$PRE1.'outlet/order_ajax/',
				$PRE1.'outlet/order_view/',
				$PRE1.'outlet/order_view_print/',
				$PRE1.'outlet/order_pay/',
				$PRE1.'outlet/order_scan/',
				$PRE1.'outlet/outstock/',
				$PRE1.'outlet/outstock_ajax/',
				$PRE1.'outlet/outstock_send/',
				$PRE1.'outlet/register/',
				$PRE1.'outlet/settle/',
				$PRE1.'outlet/getMember/',
				$PRE1.'outlet/order_refund_ajax',
				$PRE1.'outlet/search_ajax',
				$PRE1.'outlet/goods_attribute',
				$PRE1.'outlet/order_refund',
				$PRE1.'outlet/order_statistics',
				$PRE1.'outlet/order_excel',
				$PRE1.'outlet/order_statistics_excel',
				$PRE1.'outlet/order_statistics_print',
				$PRE1.'outlet/market',
            $PRE1.'repo/index',
            $PRE1.'repo/change',
            $PRE1.'repo/login',
            $PRE1.'repo/login_authorize',
            $PRE1.'repo/logout',
            $PRE1.'repo/lead/',
            $PRE1.'repo/market',
            $PRE1.'repo/order/',
            $PRE1.'repo/order_ajax/',
            $PRE1.'repo/order_view/',
            $PRE1.'repo/order_pay/',
            $PRE1.'repo/order_scan/',
            $PRE1.'repo/outstock/',
            $PRE1.'repo/outstock_ajax/',
            $PRE1.'repo/outstock_send/',
            $PRE1.'repo/outstock_order/',
            $PRE1.'repo/turnsms/',
        $PRE1.'shake/index',
        $PRE1.'shake/count_down',
        $PRE1.'shake/recScore',
        $PRE1.'shake/attention',
        $PRE1.'shake/awards',
        $PRE1.'shake/getRank',
        $PRE1.'shake/baoming',
        $PRE1.'signsort/index',
		$PRE1.'sign/signInWebPage',
            $PRE1.'review/addreview',
            $PRE1.'review/reviewafter',
            $PRE1.'review/first',
            $PRE1.'review',
        $PRE1.'chat/send',
		$PRE1.'sms/index/',
		$PRE1.'sms/send/',
		$PRE1.'sms/verify/',
		$PRE1.'store/apply/',
		$PRE1.'store/apply_add/',
		$PRE1.'wxpay/index/',
			$PRE1.'kuaidi100/index',
			$PRE1.'groupeat',
			$PRE1.'groupeat/createCard',
			$PRE1.'lotteryn/index/'

				);
	$array2 = array(
				$PRE2.'index/show?id=',
				$PRE2.'index',
				/*--------------------*/
				$PRE2.'member/cancelorder/',
				$PRE2.'member/logistics/',
				$PRE2.'member/orderconfirm/',
				$PRE2.'member/order_detail',
				$PRE2.'member/order_gift',
				$PRE2.'member/applyover/',
				$PRE2.'member/cancelapply/',
				$PRE2.'member/applymessage/',
				$PRE2.'member/apply/',
				/*------------------------*/
                $PRE2.'seckill/index',//秒杀首页
				$PRE2.'seckill/loadajax/',
				$PRE2.'member/index',
				$PRE2.'member/edit',
				$PRE2.'member/distribution_apply/',
				$PRE2.'member/distribution/',
				$PRE2.'member/collect',
				$PRE2.'member/charge_log',
				$PRE2.'member/orderpai_view?id=',
				$PRE2.'member/orderpai',
				$PRE2.'member/pai_log?id=',
				$PRE2.'member/cash_log',
				$PRE2.'member/order_view?id=',
				$PRE2.'member/order_check?id=',
				$PRE2.'member/order/',
				$PRE2.'member/sign_in',
				$PRE2.'member/integral_list',
				$PRE2.'member/coupon_view?id=',
				$PRE2.'member/coupon_check?id=',
				$PRE2.'member/coupon',
				$PRE2.'member/address',
				$PRE2.'member/address_add',
				$PRE2.'member/address_edit?id=',
				$PRE2.'member/collection',
				$PRE2.'member/discountvoucher/',
				$PRE2.'member/discountvoucher_view/',
				$PRE2.'member/register',//会员注册
				$PRE2.'member/login',//会员登录册
				$PRE2.'member/index',
				$PRE2.'albums',
				$PRE2.'albums?id=',
				$PRE2.'album?id=',
				$PRE2.'index/category?id=',
				$PRE2.'index/show',
				$PRE2.'index/show?id=',
				$PRE2.'form?id=',
				$PRE2.'card?id=',
				$PRE2.'scan?id=',
				$PRE2.'reserve',
				$PRE2.'sign?id=',
				$PRE2.'eshop/index',
				$PRE2.'eshop/show?id=',
				$PRE2.'eshop/cart',
				$PRE2.'eshop/category?id=',
				$PRE2.'eshop/tag?id=',
				$PRE2.'eshop/category_navigation',
				$PRE2.'eshop/navigation',
				$PRE2.'eshop/search',
				$PRE2.'eshop/search_ajax',
				$PRE2.'eshop/seminar',//商城专题
				$PRE2.'eshop/store_manage/',
				$PRE2.'eshop/store_index?id=',
                $PRE2.'eshop/surroundings',
                $PRE2.'mate/index?id=',
				$PRE2.'order/order_getaddr',
				$PRE2.'order/order_gift_blessing',//礼物祝福页
				$PRE2.'order/order_gift_send',//礼物分享页
				$PRE2.'order/order_gift_view',//礼物查看页
				$PRE2.'order/order_gift_get',//礼物领取页
                                $PRE2.'order/order_gift_send1',//礼物分享页
				$PRE2.'order/order_gift_view1',//礼物查看页
				$PRE2.'ggk?id=',
				$PRE2.'lottery?id=',
				$PRE2.'active?id=',
				$PRE2.'cv/index',
				$PRE2.'cv/view?id=',
				$PRE2.'present/present_info?id=',
				$PRE2.'present/present_get?id=',
				$PRE2.'present/present_doget?id=',
				$PRE2.'present/present_view?id=',
				$PRE2.'present/present_list?id=',
				$PRE2.'game?id=',
				$PRE2.'crm/login?ticket=',
				$PRE2.'task/index',
				$PRE2.'bonuses/pt?id=',
				$PRE2.'bonuses/Dbonuses?id=',
				$PRE2.'bonuses/hblist',
				$PRE2.'distribution/index/',
				$PRE2.'distribution/apply/',
				$PRE2.'distribution/manage/',
				$PRE2.'distribution/shop/',
            $PRE2.'distribution/myshop/',
				$PRE2.'distribution/edit/',
				$PRE2.'distribution/member/',
            $PRE2.'distribution/deposit/',//店铺验证
				$PRE2.'manifesto/index?id=',
				$PRE2.'manifesto/makepic?id=',
				$PRE2.'manifesto/showpic?id=',
				$PRE2.'sharepage/index?id=',
				$PRE2.'sharepage/getnum?id=',
				$PRE2.'sharepage/receiveprize?id=',
				$PRE2.'survey/index?id=',
				$PRE2.'survey/show?id=',
				$PRE2.'survey/rank?id=',
				$PRE2.'survey/content?id=',
				$PRE2.'vote/index?id=',
				$PRE2.'vote/option?id=',
				$PRE2.'coupon/category?id=',
				$PRE2.'coupon/show?id=',
				$PRE2.'coupon/buy?id=',
				$PRE2.'coupon/pay?id=',
                $PRE2.'cfund/index',
                $PRE2.'cfund/cfund_detail',
                $PRE2.'cfund/support',
                $PRE2.'cfund/support_detail',
                $PRE2.'cfund/my_item',
                $PRE2.'cfund/pay',
				$PRE2.'cfund/showMsg',
				$PRE2.'wxpay/index',
				$PRE2.'wxpay/helppayapply',
				$PRE2.'wxpay/helppay',
				$PRE2.'wxpay/recharge',
				$PRE2.'cfund/do_ajaxsigned',
            $PRE2.'estate/index',
            $PRE2.'estate/change',
            $PRE2.'estate/login',
            $PRE2.'estate/login_authorize',
            $PRE2.'estate/logout',
            $PRE2.'estate/lead/',
            $PRE2.'garden/index',
            $PRE2.'garden/change',
            $PRE2.'garden/login',
            $PRE2.'garden/login_authorize',
            $PRE2.'garden/logout',
            $PRE2.'garden/outstock_send',
            $PRE2.'park/joinpark',
            $PRE2.'park/maintain/',
            $PRE2.'newrss/index/',
            $PRE2.'outlink/index/',
            $PRE2.'webticket/index/',
            $PRE2.'webticket/login/',
			$PRE2.'webticket/accLogin/',
				$PRE2.'outlet/index',
				$PRE2.'outlet/lead',
				$PRE2.'outlet/change',
				$PRE2.'outlet/login',
				$PRE2.'outlet/login_authorize',
				$PRE2.'outlet/logout',
				$PRE2.'outlet/operate',
				$PRE2.'outlet/scanEwm',
				$PRE2.'outlet/testScan',
				$PRE2.'outlet/cart_add',
				$PRE2.'outlet/order',
				$PRE2.'outlet/order_ajax',
				$PRE2.'outlet/order_view?id=',
				$PRE2.'outlet/order_view_print?id=',
				$PRE2.'outlet/order_pay?id=',
				$PRE2.'outlet/order_scan',
				$PRE2.'outlet/outstock',
				$PRE2.'outlet/outstock_ajax',
				$PRE2.'outlet/outstock_send?id=',
				$PRE2.'outlet/register',
				$PRE2.'outlet/settle',
				$PRE2.'outlet/getMember',
				$PRE2.'outlet/order_refund_ajax',
				$PRE2.'outlet/search_ajax',
				$PRE2.'outlet/goods_attribute',
				$PRE2.'outlet/order_refund',
				$PRE2.'outlet/order_statistics',
				$PRE2.'outlet/order_excel',
				$PRE2.'outlet/order_statistics_excel',
				$PRE2.'outlet/order_statistics_print',
				$PRE2.'outlet/market',
            $PRE2.'repo/index',
            $PRE2.'repo/change',
            $PRE2.'repo/login',
            $PRE2.'repo/login_authorize',
            $PRE2.'repo/logout',
            $PRE2.'repo/lead/',
            $PRE2.'repo/market',
            $PRE2.'repo/order/',
            $PRE2.'repo/order_ajax/',
            $PRE2.'repo/order_view/',
            $PRE2.'repo/order_pay/',
            $PRE2.'repo/order_scan/',
            $PRE2.'repo/outstock/',
            $PRE2.'repo/outstock_ajax/',
            $PRE2.'repo/outstock_send/',
            $PRE2.'repo/outstock_order/',
            $PRE2.'repo/turnsms/',
        $PRE2.'shake/index',
        $PRE2.'shake/count_down',
        $PRE2.'shake/recScore',
        $PRE2.'shake/attention',
        $PRE2.'shake/awards',
        $PRE2.'shake/getRank',
        $PRE2.'shake/baoming',
        $PRE2.'signsort/index',
		$PRE2.'sign/signInWebPage',
            $PRE2.'review/addreview',
            $PRE2.'review/reviewafter',
            $PRE2.'review/first',
            $PRE2.'review',
        $PRE2.'chat/send',
		$PRE2.'sms/index/',
		$PRE2.'sms/send/',
		$PRE2.'sms/verify/',
		$PRE2.'store/apply/',
		$PRE2.'store/apply_add/',
		$PRE2.'wxpay/index/',
			$PRE2.'kuaidi100/index',
			$PRE2.'groupeat',
			$PRE2.'groupeat/createCard',
			$PRE2.'lotteryn/index?id='
				);//被替换后的地址
	
	$url = str_replace($array1, $array2, $url);
	if(is_weixin()){
            if(strpos($url,"?")){
                $url .= '&sopenid='.$_G[$mid]['openid'];
            }else{
                $url .= '?sopenid='.$_G[$mid]['openid'];
            }
	}
	return $url;
}

/*
	分享数据功能
*/
function toShare($_mid,$_openid,$_table,$_id){
	if(!$_mid || !$_openid || !$_table || !$_id) return false;
	DB::insert('wx_share',array(
								'mid'=>$_mid,
								'openid'=>$_openid,
								'tablename'=>$_table,
								'tableid'=>$_id,
								'inputtime'=>TIME
							)
				);
	return true;
}

/*
	积分设置信息
*/
function integralSetting($_mid){
	
	$r = DB::result_first('select value from %t where mid=%s',array('wx_integral_setting',$_mid));
	
	$array = $r ? json_decode($r,true) : array();
	
	if(!is_array($array)) $array = array();
	
	return $array;
	
}

/*
	单独的积分数据表
	$_mid 			平台id
	$_openid 		要操作积分的用户
	$_table
	$_id 
	$_type 			方式
	$_integral 		积分数
	$_increase 		是否重复添加 1 是 0 否
	$_fromopenid 	来源openid
	$_toopenid 		自身的openid
	$_note 			备注
*/
function plusIntegral($_mid,$_openid,$_table,$_id,$_type,$_field,$_integral,$_increase = 0,$_fromopenid = '',$_toopenid = '',$_note = ''){
	
	if(!$_mid || !$_openid || !$_integral) return false;
	
	$r = DB::result_first('select id from %t where mid=%s and tablename=%s and tableid=%s and from_openid=%s and to_openid=%s and type=%s',array('wx_integral_log',$_mid,$_table,$_id,$_fromopenid,$_toopenid,$_type));
	
	if(!$r || $_increase){
		
		$integral_type = lang('weixin_integral','integral_type');
		
		$_field = in_array($_field,$integral_type) ? $_field : 'value1';
		
		//会员积分信息
		$userinit = DB::fetch_first('select * from %t where mid=%s and openid=%s',array('wx_integral',$_mid,$_openid));
		
		if($userinit['id']){
			$userInit[$_field] = $_integral + $userinit[$_field];
			DB::update('wx_integral',$userInit,'id='.intval($userinit['id']));
		}else{
			$userInit['mid'] = $_mid;
			$userInit['openid'] = $_openid;
			$userInit[$_field] = $_integral;
			DB::insert('wx_integral',$userInit);
		}
		//获取积分设置进行增长相应的积分
		
		$sql['id'] 			= date('YmdHis').rand_str(6,true);
		$sql['_uid'] 		= $_G['_uid'];
		$sql['mid'] 		= $_mid;
		$sql['from_openid'] = $_fromopenid;
		$sql['to_openid'] 	= $_toopenid;
		$sql['tablename'] 	= $_table;
		$sql['tableid'] 	= $_id;
		$sql['type'] 		= $_type;
		$sql[$_field] 		= $_integral;
		$sql['note'] 		= $_note;
		$sql['inputtime'] 	= TIME;
		DB::insert('wx_integral_log',$sql);
		
		//plusGold($_mid,$_openid,$_integral,'jf',$_note,$_table,$_id,$_increase);
		
		return true;
		
	}else return false;
}

//------------------------

//-----------------------------
/*
	增加或减少余额
	mid      客户标识
	openid   会员标识
	type     类型 ye:余额  jf:积分
	note     备注
	table    表名
	id       对应表id
	increase 是否重复提交(必须有table 和id的时候)
*/
function plusGold($mid,$openid,$amount,$type = 'ye',$note ='',$table = '',$id = 0,$increase = 1){
	global $_G;
	$wxuser = getUser($openid,$mid);
	if(!$wxuser) return false;
	$update = array();
	//余额
	if($type == 'ye'){
		if($amount && is_numeric($amount)){
			if(($amount < 0 && $wxuser['ye'] >= $amount) || $amount > 0){
				$update['ye'] = $wxuser['ye'] + $amount;
				$insert_ye['uid'] = $_G['uid'];
				$insert_ye['mid'] = $mid;
				$insert_ye['openid'] = $openid;
				$insert_ye['type'] = 'ye';
				$insert_ye['amount'] = $amount;
				$insert_ye['inputtime'] = TIME;
				$insert_ye['note'] = $note;
				$insert_ye['tablename'] = $table ? $table : '';
				$insert_ye['tableid'] = $id ? $id : '';
				DB::insert('wx_charge', $insert_ye);
			}else{
				return false;	
			}
		}else{
			return false;	
		}
	}
	//积分
	if($type == 'jf'){
		if($amount && is_numeric($amount)){
			if(($amount < 0 && $wxuser['jf'] >= $amount) || $amount > 0){
				if($table && $id && !$increase){
					$incre = DB::fetch_first('select * from %t where mid=%s and openid=%s and type=%s and tablename=%s and tableid=%d', array('wx_charge',$mid,$openid,'jf',$table,$id));
					if($incre){
						return false;
					}
				}
				$update['jf'] = $wxuser['jf'] + $amount;
				$insert_jf['uid'] = $_G['uid'];
				$insert_jf['mid'] = $mid;
				$insert_jf['openid'] = $openid;
				$insert_jf['type'] = 'jf';
				$insert_jf['amount'] = $amount;
				$insert_jf['inputtime'] = TIME;
				$insert_jf['note'] = $note;
				$insert_jf['tablename'] = $table ? $table : '';
				$insert_jf['tableid'] = $id ? $id : '';
				DB::insert('wx_charge', $insert_jf);
			}else{ 
				return false;	
			}
		}else{
			return false;	
		}
	}
	if(count($update) > 0){
		DB::update('wx_wxuser', $update, "mid='".$mid."' and openid='".$openid."'");
		return true;
	}
	return false;
}


//exit 返回jsonp形式
function exit_jsonp($val,$callback='callback'){
    global $_G;
    if(is_array($val)){
        $val = json_encode($val);
    }
    if($_G['inajax']){
        echo $val;
        exit;
    }
//callback 只能由字母,数字，下划线组成，并且以字母或下划线开头
    if(!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]+$/', $callback)){
        $callback='callback';
    }
    header('Content-type: text/javascript');
    $callback = urlencode($callback); 
    echo "window[decodeURIComponent('{$callback}')]({$val})";
    exit;
}


/*	截取字符串
*	$sourcestr 	需要截取的字符串
*	$cutlength	截取的长度
*	$nohtml		是否带html标签 默认 不带
*	$laststr	截取长度小于字符串长度是 后面加的后缀 默认 ...
*/
function Web_substr_cut_str($sourcestr,$cutlength=0,$nohtml=1,$laststr='...'){	
	if($nohtml) $sourcestr = strip_tags($sourcestr,'');
	$returnstr='';
	$i=0;
	$n=0;
	$str_length=strlen($sourcestr);//字符串的字节数
	while ((($n < $cutlength)||!$cutlength) and ($i <= $str_length)){
		$temp_str=substr($sourcestr,$i,1);
		$ascnum=ord($temp_str);//得到字符串中第$i位字符的ascii码
		if ($ascnum>=224){//如果ASCII位高与224，
			$returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
			$i=$i+3; //实际Byte计为3
			$n++; //字串长度计1
		}elseif ($ascnum>=192){//如果ASCII位高与192，
			$returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
			$i=$i+2; //实际Byte计为2
			$n++; //字串长度计1
		}elseif ($ascnum>=65 && $ascnum<=90){//如果是大写字母，
			$returnstr=$returnstr.substr($sourcestr,$i,1);
			$i=$i+1; //实际的Byte数仍计1个
			$n++; //但考虑整体美观，大写字母计成一个高位字符
		}else{//其他情况下，包括小写字母和半角标点符号，
			$returnstr=$returnstr.substr($sourcestr,$i,1);
			$i=$i+1; //实际的Byte数计1个
			$n=$n+0.5; //小写字母和半角标点等与半个高位字符宽...
		}
	}
	if ($str_length>$i){
		$returnstr = $returnstr . $laststr;//超过长度时在尾处加上后缀
	}
	return $returnstr; 
}
/*
	php自身生成二维码
	$_content 二维码内容
	$_matrixPointSize 生成图片大小
	$_errorCorrectionLevel 容错级别
*/
function phpQrCode($_content,$_matrixPointSize = 6,$_errorCorrectionLevel = 'L'){
	QRcode::png($_content,false,4,10,2);
}

/*---------------
 * 
 *订单记录
 * $functionname来源方法名   
 * $id 订单id， 
 * $tablename 操作表名,
 * $tableid 操作表id,
 * $note 操作行为  
 * $notice是否通知会员 
 * $extkey 如果存在 $id等于 $tablename下 $extkey字段的值
 * 
 */
function addOrderLog($functionname='',$id='',$tablename='',$tableid='',$note='',$notice=0,$extkey=''){
    global $_G,$mid;
    if(!$functionname || !$id || !$tablename || !$tableid || !$note ){
        echo 'addOrderLog_error';
        //exit;
    }
    if(is_array($note)){
        $note = json_encode($note);
    }
    $log = array();
    $log['mid'] = $mid;
    $log['inputtime'] = $log['updatetime'] = TIME;
    $log['uid'] = $_G['uid'];
    $log['_uid'] = $_G['_uid'];
    $log['order_id'] = $id;
    $log['fromfunction'] = $functionname;
    $log['fromsite'] = 0;
    $log['tablename'] = $tablename;
    $log['tablekey'] = $extkey;
    $log['tableid'] = $tableid;
    $log['note'] = $note;
    $log['notice'] = $notice;
    $log['clientip'] = $_G['clientip'];
    DB::SetMainDB(DB_ESHOP);
    DB::insert('es_order_log',$log);
}
function web_curl($url,$post_data = array()){		
	$get_content = DoCurl($url, $post_data);
	return json_decode($get_content,true);
}
function web_GetAccess_token($mid = ''){
	global $_G,$_mid;
	if($mid) $_mid = $mid;
	DB::query("delete FROM %t where mid=%s and `inputtime` <= %d", array('wx_access_token',$_mid ,TIME-6000));
	$token = DB::fetch_first("select `access_token` from %t where mid=%s and `inputtime` > %d", array('wx_access_token',$_mid ,TIME-6000));
	//var_dump($token);
        if($token){
		$access_token = $token['access_token'];
	}else{
		if(!$_G['wxapi']['AppId'] || !$_G['wxapi']['AppSecret']){
			$r = DB::fetch_first('select AppId,AppSecret from %t where mid=%s', array('wx_apiuser', $_mid));
			//var_dump($r);
                        if(!$r) return false;
			$_G['wxapi'] = array('AppId'=>$r['AppId'],'AppSecret'=>$r['AppSecret']);
		}
		$d = web_curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$_G['wxapi']['AppId']."&secret=".$_G['wxapi']['AppSecret']);
		//var_dump($d);
                if(is_array($d) && $d['access_token']){
			DB::insert('wx_access_token',	array('access_token'=>$d['access_token'] ,'mid'=>$_mid , 'inputtime'=>TIME ) );
			$access_token = $d['access_token'];
		}elseif(($jsond = json_decode($d,true)) && !isset($jsond['errcode'])){
                    DB::insert('wx_access_token',array('access_token'=>$jsond['access_token'] ,'mid'=>$_mid , 'inputtime'=>TIME ) );
                    $access_token = $jsond['access_token'];
		}
	}
        
	if($access_token) return $access_token;
	else return false;
}
function web_GetWxuser($_mid,$_openid){
	global $_G;
	if(!$_openid) return false;
	$access_token = active_check_access_token($_mid);
        if(!$access_token){
		return false;
	}
	$d = web_curl('https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$_openid.'&lang=zh_CN');
	    //var_dump($d);
	if(!$d['errcode']){
		$user = $d;
		$r = DB::result_first('select openid from %t where mid=%s and openid=%s limit 1',array('wx_wxuser',$_mid,$_openid));
		if(!$r) DB::insert('wx_wxuser',array('openid'=>$_openid,'mid'=>$_mid,'subscribe'=>$user['subscribe']));
		if(count($user)>0){
			$updata = array(
					'subscribe'=>$user['subscribe'],
					'nickname'=>new_addslashes($user['nickname']),
					'sex'=>$user['sex'],
					'city'=>$user['city'],
					'country'=>$user['country'],
					'province'=>$user['province'],
					'language'=>$user['language'],
					'headimgurl'=>$user['headimgurl'],				
					'unionid'=>$user['unionid'],
					'localimg'=>'',
					'sj_openid'=>$user['sj_openid']
					);
			if($user['subscribe_time']) $updata['subscribe_time'] = $user['subscribe_time'];
			DB::update('wx_wxuser', $updata ,DB::format('openid=%s and mid=%s',array($_openid,$_mid)));
		}
		return true;
	}else return false;
}

/*  *
评论自动处理
 *  */
function Review_update($_mid,$_storeid=0){
    if(!$_mid) return false;
    $setiing = C::t('#api#review')->getReviewSettingM($_storeid);
    if($setiing['id'] && $setiing['auto_review_time']){
        $auto_review_time = TIME - $setiing['auto_review_time']; //自动好评时间
        
        //取出未评论的订单详细
        DB::SetMainDB(3);
        $order_detail = DB::fetch_all('SELECT id,order_id,goods_id,openid FROM %t where mid=%s and store_id=%d and comment_status=0 and detail_status=1',array('es_order_detail',$_mid,$_storeid));
        $order_array = array(); //到时间的订单组
        $order_illegal_array = array(); //没有到时间或者无效的订单组
        foreach($order_detail as $k => $v){
            if(!$order_illegal_array[$v['order_id']]){
                continue;
            }
            if(!$order_array[$v['order_id']]){
                $order_array[$v['order_id']] = DB::fetch_all('select `id`,`success_time` from %t '
                        . 'where mid=%s and store_id=%d and openid=%s and id=%s and order_status=1 and success_time<=%d ',array('es_order',$_mid,$_storeid,$v['openid'],$v['order_id'],$auto_review_time));
                if(empty($order_array[$v['order_id']])){
                    $order_illegal_array[$v['order_id']] = 1;
                    continue;
                }
            }
            if($order_array[$v['order_id']]){
                $update_detail = array();
                $update = array();
                $update_detail['comment_status'] = 1;
                $update_detail['updatetime'] = TIME;
                DB::SetMainDB(3);
                DB::update('es_order_detail', $update_detail,'id='.$v['id']);
                addOrderLog(__FUNCTION__,$order_id,'es_order_detail',$k, $update_detail);//记录行为
                $update['inputtime'] = $update['updatetime'] = TIME;
                $update['status'] = 1;
                $update['content'] = '好评！';
                $update['attitude'] = 5;
                $update['openid'] = $v['openid'];
                $update['mid'] = $_mid;
                $update['store_id'] = $_storeid;
                $update['order_id'] = $v['order_id'];
                $update['detail_id'] = $v['id'];
                $update['goods_id'] = $v['goods_id'];
                $update['anonym'] = 1;
                $update['systematic'] = 1;
                $update['systematic_time'] = $order_array[$v['order_id']]['success_time'] + $setiing['auto_review_time'];
                $update['systematic_real_time'] = TIME;
                DB::SetMainDB(3);
                DB::insert('es_order_review', $update);
            }

        }
    }
}

function checkotrigger($mid,$id){
	if(!in_array($mid,array('SPEGEKIGFN','RDOXYKDTTD'))){
		//return false;
	}
	if(!$mid || !$id){
		return false;	
	}
	
	
	DB::SetMainDB(3);
	$order = DB::fetch_first('select openid,order_status,pay_status,send_status,openid,create_time,pay_time,send_time,success_time,total_actual_pay from %t where mid=%s and id=%s',array('es_order',$mid,$id));
	if(!$order){
		return false;	
	}
	
	$x_bool = true;
	
	if($order['pay_status']==1) $p_bool = true;
	else $p_bool = false;
	
	//$s_bool = true;
	
	if($order['order_status']==1) $o_bool = true;
	else $o_bool = false;
	
    DB::SetMainDB(3);
	$o_handle = DB::fetch_all("select handle from %t where order_id=%s and mid=%s and status=1 and display=1",array("es_otrigger_log",$id,$mid));
	
	
	foreach($o_handle as $success){
		if($success['handle'] == 1){
			$x_bool = false;
		}
		if($success['handle'] == 2){
			$p_bool = false;
		}
		/*if($success['handle'] == 3){
			$s_bool = false;
		}*/
		if($success['handle'] == 4){
			$o_bool = false;
		}
	}
	
	
	if($x_bool){
		insertootriggerlog(1,$order,$mid,$id);
	}
	if($p_bool){
		insertootriggerlog(2,$order,$mid,$id);
	}
	/*if($s_bool){
		insertootriggerlog(3,$order,$mid,$id);
	}*/
	if($o_bool){
		insertootriggerlog(4,$order,$mid,$id);
	}
	
}
//插入订单活动记录
function insertootriggerlog($handle,$order,$mid,$id){
	
	DB::SetMainDB(3);
    //$oh = DB::fetch_all("select `id`,`title`,`handle`,`time_type`,`btime`,`etime`,`price_type`,`min_price`,`max_price`,`trigger_type`,`trigger_id`,`trigger_other`,`trigger_filed`,`trigger_num`,`limit_group` from %t where mid=%s and handle=%d and status=1 and display=1",array("es_otrigger",$mid,$handle));
	$oih = DB::fetch_all("select `id`,`title`,`handle`,`time_type`,`btime`,`etime` from %t where mid=%s and handle=%d and status=1 and display=1",array("es_otrigger_important",$mid,$handle));
	if(!$oih) return false;
	//没有限制是否关注  如果需要之后加上
	$groupid = DB::result_first('select groupid from %t where mid=%s and openid=%s',array('wx_wxuser',$mid,$order['openid']));
   	foreach($oih as $ih){
		$order_time = '';
		$isfalse = 0;
		switch($ih['time_type']){
			case 1:
				$order_time = $order['create_time'];
				break;
			case 2:
				$order_time = $order['pay_time'];
				break;
			case 3:
				$order_time = $order['send_time'];
				break;
			case 4:
				$order_time = $order['success_time'];
				break;
			default:
				$isfalse = 1;
				break;
		}
		if($isfalse){
			continue;	
		}
		if($order_time < $ih['btime'] || $order_time >= $ih['etime']){
			continue;
		}
		
		
		DB::SetMainDB(3);
		$h = DB::fetch_first("select `id`,`min_price`,`trigger_type`,`trigger_id`,`trigger_other`,`trigger_filed`,`trigger_num`,`limit_group` from %t where mid=%s and important_id=%d and min_price<=%d and (limit_group=-1 or limit_group=%d) and status=1 and display=1 order by min_price desc",array("es_otrigger",$mid,$ih['id'],$order['total_actual_pay'],$groupid));	
		if(!$h){
			continue;	
		}
		$isfalse = 0;
		switch($h['trigger_type']){
			case 'coupon':
				$rcoupon = discountvoucher_get($h['trigger_id'],$mid,$order['openid']);
				$logid = intval($rcoupon['id']);
				break;
			case 'event':
				$revent = trigger_event($h['trigger_id'],$mid,$order['openid']);
				$revent = $revent?json_decode($revent,true):array();
				$revent = is_array($revent) ? $revent : array();
				$logid = intval($revent['activeid']);
				break;
			case 'balance':
				$trigger_num = intval($h['trigger_num']);
				if($trigger_num <= 0){
					$isfalse = 1;
					break;
				}
				$ye = DB::result_first('select ye from %t where mid=%s and openid=%s',array('wx_wxuser',$mid,$order['openid']));
				$ye = $ye + $trigger_num;
				DB::update('wx_wxuser', array('ye'=>$ye), "mid='".$mid."' and openid='".$order['openid']."'");
				$logid = $ye;
				break;
			case 'integral':
				$trigger_num = intval($h['trigger_num']);
				if(!in_array($h['trigger_filed'],array('value1','value2','value3','value4','value5','value6','value7','value8'))){
					$isfalse = 1;	
					break;
				}
				if($trigger_num <= 0){
					$isfalse = 1;
					break;
				}
				//会员积分信息
				$userinit = DB::fetch_first('select * from %t where mid=%s and openid=%s',array('wx_integral',$mid,$order['openid']));
				$userInitArr = array();
				if($userinit['id']){
					$userInitArr[$h['trigger_filed']] = $trigger_num + $userinit[$h['trigger_filed']];
					DB::update('wx_integral',$userInitArr,'id='.intval($userinit['id']));
				}else{
					$userInitArr['mid'] = $mid;
					$userInitArr['openid'] = $order['openid'];
					$userInitArr[$h['trigger_filed']] = $trigger_num;
					$userinit['id'] = DB::insert('wx_integral',$userInit,true);
				}
				$logid = $userInitArr[$h['trigger_filed']];
				break;
			default:
				$isfalse = 1;
				break;	
		}
		
		if($isfalse){
			continue;	
		}
		$insert = array();
		$insert = $h;
		unset($insert['id']);
		$insert = array_merge($h,$ih);
		unset($insert['id']);
		
		$insert['mid'] = $mid;
		$insert['oi_id'] = $ih['id'];
		$insert['otrigger_id'] = $h['id'];
		$insert['order_id'] = $id;
		$insert['time_time'] = $order_time;
		$insert['money'] = $order['total_actual_pay'];
		$insert['openid'] = $order['openid'];
		$insert['log_id'] = $logid;
		$insert['inputtime'] = TIME;
		DB::SetMainDB(3);
		DB::insert("es_otrigger_log", $insert);	
	}
	return false;
}

//发送优惠券
function discountvoucher_get($id,$mid,$openid){
	//发送优惠券信息
	$r = C::t('#weixin#eshop')->getDiscountvoucherM($mid,$id);

	$sql['coupon_id']			= $id;
	$sql['title']				= $r['title'];
	$sql['description']			= $r['description'];
	$sql['thumb']				= $r['thumb'];
	$sql['price']				= $r['price'];
	$sql['limit_price']			= $r['limit_price'];
	$sql['limit_user']			= $r['limit_user'];
	$sql['btime']				= $r['btime'];
	$sql['etime']				= $r['etime'];
	$sql['limit_btime']			= $r['limit_btime'];
	$sql['limit_etime']			= $r['limit_etime'];
	$sql['isget']				= $r['isget'];
	$sql['no_discount_group']	= $r['no_discount_group'];
	$sql['mid']					= $mid;
	$sql['openid']				= $openid;
	$sql['inputtime'] 			= TIME;
	$sql['status'] 				= 1;
	$sql['display'] 			= 1;
	DB::SetMainDB(3);
	$logid = DB::insert('es_coupon_log',$sql,true);

	return array('Error'=>0,'Msg'=>'操作成功','id'=>$logid);

}
//触发事件
function trigger_event($id,$mid,$openid){
	if($openid){
		if($id){
			$event = DB::fetch_first('select id,type from %t where mid=%s and id=%d and display=1',array('wx_event',$mid,$id));
        }
        if($event){
			//判断是否是我说的话
		if($event['type'] == 'text'){
			$bind = DB::fetch_first('select * from %t where tablename=%s and type=%s and tableid=%d and mid=%s and display=1',array('wx_bind', 'wx_event', 'text', $event['id'], $mid));
			if($bind) $msg = $bind['content'];
				$msg ? $r = DoCurl('http://10.252.85.65/active_add.php?api=custom_send', array('mid'=>$mid,'openid'=>$openid,'msgtype'=>'text','content'=>$msg)) : '';
			}else{
				$bind = DB::fetch_all('select * from %t where tablename=%s and tableid=%d and mid=%s and display=1 order by turn desc',array('wx_bind', 'wx_event', $event['id'], $mid));
				$msg = array();
				foreach($bind as $v){
					$msg[] = array('title'=>$v['title'],'description'=>$v['content'],'picurl'=>$v['thumb'],'url'=>$v['url']);
				}
				$msg ? $r = DoCurl('http://10.252.85.65/active_add.php?api=custom_send', http_build_query(array('mid'=>$mid,'openid'=>$openid,'msgtype'=>'news','content'=>$msg))) : '';
			}
		}
	}
	return $r;
}


//获取 企业信息 apiuser
function active_get_apiuser($mid = '', $zd = '') {
    if (!$mid) {
        global $_G;
        $mid = $_G['g_mid'];
    }
    if (!$mid) {
        return array('errcode' => 1, 'errmsg' => '获取公众号信息 参数MID丢失');
    }
    //$d = memory('get', 'wx-apiuser-' . $mid);

    if (!$d) {
        //DB::setRead();
        $d = DB::fetch_first('select * from %t where mid=%s', array('wx_apiuser', $mid));
        /*if ($d)
            memory('set', 'wx-apiuser-' . $mid, $d);*/
    }
    if (!$d) {
        return array('errcode' => 1, 'errmsg' => '获取公众号信息失败');
    }
    $data = array();
    if (empty($zd)) {
        $data = $d;
    } else {
        if (!is_array($zd)) {
            $zd = explode(',', $zd);
        }
        foreach ($zd as $k => $v) {
            $data[$v] = $d[$v];
        }
        if (count($zd) === 1) {
            $data = current($data);
        }
    }
    return $data;
}

function active_get_component_access_token($AppIdC = 1, $qz = 0) {
    global $_G;
    $AppConfig = $_G['config']['AppConfig'][$AppIdC];
    $appid = $AppConfig['AppID'];
    $appsecret = $AppConfig['AppSecret'];
    if (!$appid) {
        return array('errcode' => 300, 'errmsg' => 'NO APPID');
    }
    //$d = memory('get', 'wx-authorize_component_access_token-' . $appid);
    if (!$d || (TIME - $d['inputtime'] > 6000) || $qz) {
        //DB::setRead();
        $d = DB::fetch_first('select * from %t where appid=%s', array('wx_authorize_component_access_token', $appid));
        if ($d && (TIME - $d['inputtime']) < 6000 && !$qz) {
            //memory('set', 'wx-authorize_component_access_token-' . $appid, $d);
            return $d['component_access_token'];
        }
        $id = $d['id'];
      // memory('rm', 'wx-authorize_component_access_token-' . $appid);
        $component_verify_ticket = active_get_componentverifyticket($AppIdC);
        if (is_array($component_verify_ticket) && $component_verify_ticket['errcode']){
            return $component_verify_ticket;
        }
        $post_data['component_appid'] = $appid;
        $post_data['component_appsecret'] = $appsecret;
        $post_data['component_verify_ticket'] = $component_verify_ticket;
        $d = active_curl('https://api.weixin.qq.com/cgi-bin/component/api_component_token', json_encode($post_data));
		/*if($_G[$_GET['mid']]['openid'] == 'o6aCkjgr1DZ61bE2hQosrpLteYlk'){
			//echo (TIME - $d['inputtime']); 
			//echo '1';
			var_dump($d);
			//echo $d['inputtime'].'#';
			//var_dump($apiuser);
		}*/
        if (is_array($d) && $d['component_access_token']) {
            if ($id) {
                DB::update('wx_authorize_component_access_token', array('component_access_token' => $d['component_access_token'], 'expires_in' => $d['expires_in'], 'data' => json_encode($d), 'appid' => $appid, 'inputtime' => TIME), 'id='. $id);
            } else {
                DB::insert('wx_authorize_component_access_token', array('component_access_token' => $d['component_access_token'], 'expires_in' => $d['expires_in'], 'data' => json_encode($d), 'appid' => $appid, 'inputtime' => TIME));
            }
        }
        active_addAuthorize_log($d, 'api_component_token', $appid, intval($d['errcode']), $d['component_access_token']);
    }
    if (is_array($d) && $d['errcode']) {
        return $d;
    } elseif ($d) {
        return $d['component_access_token'];
    } else {
        return array('errcode' => 1, 'errmsg' => 'component_access_token获取失败');
    }
}
//原微信curl 方法  远程访问接口用
function active_curl($url, $post_data = array()) {
    try {
        global $mid;
        //获取Cookie
        $clientkey = getcookie('memberKey_'.$mid);
        //转换Cookie
        list(,,,$pctoken) = explode("\t", SING_auth($clientkey,'DECODE',getglobal('cookiepre','config/cookie')));
        
            
        
        if(is_array($post_data)){
            if($pctoken){
                $post_data['pctoken'] = $pctoken;
            }
            $post_data['sourcet'] = 'pc';
        }else{
            if($pctoken){
                $post_data .= strlen($post_data)>0?'&':'';
                $post_data .= http_build_query(array('pctoken'=>$pctoken));
            }
            $post_data .= strlen($post_data)>0?'&':'';
            $post_data .= http_build_query(array('sourcet'=>'pc'));
        }
        $get_content = DoCurl($url, $post_data);
//        if(strpos($url,'storeorderback')!==false){
//            var_dump($get_content);
//        }
        return json_decode($get_content, true);
    } catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
    }
}
function active_addAuthorize_log($d, $api = '', $appid = '', $errcode = 0, $maininfo = '') {
    return false;
    if (!$d) {
        return false;
    }
    global $_G;
    $mid = $_G['g_mid'];
    $uid = $_G['_uid'];
    $zdarr = array('api', 'errcode', 'data', 'maininfo', 'appid', 'uid', 'mid', 'inputtime');
    $insert = array();
    foreach ($zdarr as $v) {
        switch ($v) {
            case 'inputtime':
                $insert[$v] = TIME;
                break;
            case 'data':
                $insert[$v] = is_array($d) ? json_encode($d) : $d;

                break;
            default:
                $insert[$v] = is_array($d) ? (isset($d[$v]) ? $d[$v] : $$v) : $$v;
                break;
        }
    }
    DB::insert('wx_authorize_log', $insert);
    return true;
}
//获取10分钟推送信息
function active_get_componentverifyticket($AppIdC = 1) {
    global $_G;
    $AppConfig = $_G['config']['AppConfig'][$AppIdC];
    $appid = $AppConfig['AppID'];
    if (!$appid)
        return array('errcode' => 300, 'errmsg' => 'NO APPID');
    //$d = memory('get', 'wx-authorize_component_verify_ticket-' . $appid);
    //有效时间为 10 分钟
    if (!$d || (TIME - $d['createtime'] > 600)) {
        DB::setRead();
        $d = DB::fetch_first('select * from %t where appid=%s', array('wx_authorize_component_verify_ticket', $appid));
        if ($d) {
            //memory('set', 'wx-authorize_component_verify_ticket-' . $appid, $d);
        } else {
            //memory('rm', 'wx-authorize_component_verify_ticket-' . $appid);
            return array('errcode' => 300, 'errmsg' => 'NO COMPONENT_VERIFY_TICKET');
        }
    }
    return $d['component_verify_ticket'];
}





//自动返回access_token 授权返回 和 未授权返回
function active_check_access_token($mid = '', $qz = 0) {
    if (!$mid) {
        global $_G;
        $mid = $_G['g_mid'];
    }
    if (!$mid) {
        return array('errcode' => 1, 'errmsg' => '获取access_token 参数MID丢失');
    }
    
    $apiuser = active_get_apiuser($mid);
    //var_dump($apiuser);
    if (is_array($apiuser) && $apiuser['errcode']) {
        return $apiuser;
    }
    
    
    
    if ($apiuser['isauthorize']) {
        $access_token = active_get_authorizer_access_token($mid,$apiuser['AppIdC'] ,$qz);
    } else {
        
        $access_token = active_GetAccess_token($mid, $qz);
        
    }
    return $access_token;
}
function active_GetAccess_token($mid = '', $qz = 0) {
    global $_G;
	$qz = 1;
    if (!$mid) {
        //global $_G;
        $mid = $_G['g_mid'];
    }
    if (!$mid) {
        return array('errcode' => 1, 'errmsg' => '获取access_token 参数MID丢失');
    }
    $losetime = TIME - 6000;
    //$d = memory('get', 'wx-access_token-' . $mid);

    if (!$d || $d['inputtime'] < $losetime || $qz) {
        //DB::query("delete FROM %t where mid=%s and `inputtime` <= %d", array('wx_access_token',$mid ,TIME-6000));
        //DB::SetMainDB(3);
	$d = DB::fetch_first("select * from %t where mid=%s and `inputtime` > %d", array('wx_access_token', $mid, $losetime));
        if ($d && $d['inputtime'] > $losetime && !$qz) {
            //memory('set', 'wx-access_token-' . $mid, $d);
        } else {
            
            //memory('rm', 'wx-access_token-' . $mid);
            //DB::SetMainDB(3);
            DB::query("delete FROM %t where mid=%s ", array('wx_access_token', $mid));
            $apiuser = active_get_apiuser($mid);
            if (is_array($apiuser) && $apiuser['errcode']) {
                return $apiuser;
            }
            if (!$apiuser['AppId']) {
                return array('errcode' => 1, 'errmsg' => '未设置AppId');
            }
            if (!$apiuser['AppSecret']) {
                return array('errcode' => 1, 'errmsg' => '未设置AppSecret');
            }
            
            $d = active_curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$apiuser['AppId']."&secret=".$apiuser['AppSecret']);
            
            if (is_array($d) && $d['access_token']) {
				//DB::SetMainDB(3);
                DB::insert('wx_access_token', array('access_token' => $d['access_token'], 'mid' => $mid, 'inputtime' => TIME));
            }
        }
    }
    if (is_array($d) && $d['errcode']) {
        return $d;
    } elseif ($d) {
        return $d['access_token'];
    } else {
        return array('errcode' => 1, 'errmsg' => 'access_token获取失败');
    }
}
//获取授权方 授权令通过刷新令牌获取信息    授权公众号 的 access_token
function active_get_authorizer_access_token($mid = '', $AppIdC = 1,$qz = 0) {
    global $_G;
    if (!$mid) {
        $mid = $_G['g_mid'];
    }
    if (!$mid) {
        return array('errcode' => 1, 'errmsg' => '参数MID丢失');
    }
    $AppConfig = $_G['config']['AppConfig'][$AppIdC];
    $appid = $AppConfig['AppID'];
    
	if(!$appid || !$mid){
        return array('errcode' => 300, 'errmsg' => 'NO APPID MID');
	}
    
	//$d = memory('get', 'wx-authorize_access_token-' . $mid . '-' . $appid);
    if (!$d || (TIME - $d['inputtime'] > 6000) || $qz) {
        $d = DB::fetch_first('select * from %t where mid=%s', array('wx_authorize_access_token', $mid));       
        if ($d && (TIME - $d['inputtime']) < 6000 && !$qz) {
           // memory('set', 'wx-authorize_access_token-' . $mid . '-' . $appid, $d);
            return $d['authorizer_access_token'];
        }
        //memory('rm', 'wx-authorize_access_token-' . $mid . '-' . $appid);
        DB::delete('wx_authorize_access_token', " mid='" . $mid . "'");

        $component_access_token = active_get_component_access_token($AppIdC);
        if (is_array($component_access_token) && $component_access_token['errcode']) {
            return $component_access_token;
        }
        $post_data['component_appid'] = $appid;
        $apiuser = active_get_apiuser($mid, array('AppId', 'authorizer_refresh_token'));
        if (is_array($apiuser) && $apiuser['errcode']) {
            return $apiuser;
        }
        $post_data['authorizer_appid'] = $apiuser['AppId'];
        $post_data['authorizer_refresh_token'] = $apiuser['authorizer_refresh_token'];
       
        $d = active_curl('https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' . $component_access_token, json_encode($post_data));
       /*if($_G[$_GET['mid']]['openid'] == 'o6aCkjgr1DZ61bE2hQosrpLteYlk'){
			//echo (TIME - $d['inputtime']); 
			echo '1';
			//var_dump($d);
			//var_dump($component_access_token);
			//echo $d['inputtime'].'#';
			//var_dump($apiuser);
		}*/
        if ($d['authorizer_access_token']) {
            $insert_act = array();
			$insert_act['mid'] = $mid;
			//$insert_act['appid'] = $appid;
            $insert_act['authorizer_access_token'] = $d['authorizer_access_token'];
            $insert_act['authorizer_refresh_token'] = $d['authorizer_refresh_token'];
            $insert_act['expires_in'] = $d['expires_in'];
            $insert_act['inputtime'] = TIME;
            DB::insert('wx_authorize_access_token', $insert_act);
        }
        active_addAuthorize_log($d, 'api_authorizer_token', $appid, intval($d['errcode']), $d['authorizer_access_token']);
    }
    if (is_array($d) && $d['errcode']) {
        return $d;
    } elseif ($d) {
        return $d['authorizer_access_token'];
    } else {
        return array('errcode' => 1, 'errmsg' => 'authorizer_access_token获取失败');
    }
}


/*------------同步部分 wxweb function_eb 是主方法（只修改这部分）  其他地方在这复制------*/

/*
 *  设置读取缓存 固定时间自动丢弃并删除缓存
 */
function autoMemory($method,$fileName,$data=Null){
    if(!$method || !$fileName){
        return false;
    }
    $autoUpdateTime = 86400; //固定时间自动更新缓存
    switch($method){
        case 'get':
            $return = memory('get',$fileName);
            if($return[1] && ($return[1] + $autoUpdateTime) >= TIME){
                return $return[0];
            }elseif($return){
                memory('rm',$fileName);
            }
            break;
        case 'set':
            $setData = array($data,TIME);
            memory('set',$fileName,$setData);
            break;
    }
    return false;
}

/*------------------------*/

//向用户发送消息
function sendMSG($mid, $openid, $content, $type){
	global $_G,$_mid;
	$content = str_replace("\r\n","\n",$content);
	$str = '';
	switch($type){
		//文本
		case 'text':
			$sql['type'] = 1;
			$str .= '{"touser":"'.$openid.'","msgtype":"text","text":{"content":"'.$content.'"}}';
			break;
		//图片
		//case 'image': ;break;
		//图文
		case 'news':
			$sql['type'] = 2;
			$str .= '{"touser":"'.$openid.'","msgtype":"news","news":{"articles":['.$content.']}}';
			break;
	}

	if($access_token = web_GetAccess_token($mid)){

		$post = array('touser'=>$openid,'msgtype'=>'text','text'=>$openid);

		$d = DoCurl('https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token,$str);
		$return = $d ? json_decode($d,true) : array();

		$status = ($return['errcode'] == 0) ? 1 : 0;


		if($status){
			return true;
		}else{
			return false;
		}
	}else{
		//DB::update('wx_send_log',array('error_code'=>0,'error_msg'=>'token获取失败','updatetime'=>TIME),"id=".$id);
		return false;
	}

	function fetchScanDir($prefix = 'dbt_order',$dir = 'module/api/class/dbt' , $ext='.php'){
		$r = array();
		$systemDir = APP_ROOT.DIRECTORY_SEPARATOR.$dir;
		//$systemDir = $dir;
		if(is_dir($systemDir)){
			if($files = scandir($systemDir)) {
				$isDbt = substr($prefix,0,4) == 'dbt_';
				$fixLen = strlen($prefix);
				$extLen = strlen($ext);
				foreach($files as $k=>$v){
					if($prefix && $prefix == substr($v,0,$fixLen)){
						if($extLen && $ext == substr($v,$extLen*-1) ){
							$r[] = array(
									'fullName' =>$v,
									'fixName' => substr($v,$fixLen,$extLen*-1),
									'dbtName' => $isDbt?substr($v,4,$extLen*-1):''
							);
						}

					}

				}
			}
		}
		return $r;
	}
}